package com.bing.task.v1;

import com.bing.Utils;
import com.bing.entity.Account;
import com.bing.entity.Question;
import com.bing.entity.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.RecursiveTask;

/**
 * Created by kaibb on 15-11-14.
 */
public class FetchParseQuestionAid extends RecursiveTask<QuestionResult> {
    private static final Logger LOGGER = LoggerFactory.getLogger(FetchParseQuestionAid.class);
    private List<Question> questions;

    public FetchParseQuestionAid(List<Question> questions) {
        this.questions = questions;
    }

    @Override
    protected QuestionResult compute() {
        if (questions.size() <= 20) {
            QuestionResult questionResult = new QuestionResult();
            Set<Account> accounts=new HashSet<Account>();
            for (Question question : questions) {
                Utils.fetchQuestionAID(question);
                Account account = new Account();
                account.setStatus(Status.INIT);
                account.setNoteStatus(Status.INIT);
                account.setReviewStatus(Status.INIT);
                account.setUid(question.getAid());
                accounts.add(account);
            }
            questionResult.addQuestions(questions);
            questionResult.addAccounts(accounts);
            LOGGER.info("子任务完成。");
            return questionResult;
        }
        FetchParseQuestionAid left = new FetchParseQuestionAid(questions.subList(0, questions.size() / 2));
        left.fork();
        FetchParseQuestionAid right = new FetchParseQuestionAid(questions.subList(questions.size() / 2, questions.size()));
        right.fork();
        QuestionResult leftJoin = left.join();
        QuestionResult rightJoin = right.join();

        return leftJoin.addQuestionResult(rightJoin);
    }
}
